package api

import (
	"github.com/gin-gonic/gin"
	"guard/internal/app/user/models"
	"guard/internal/errors"
	"guard/internal/request"
	"guard/internal/result"
	"net/http"
)

/*
*
用户管理
*/
func userPage(c *gin.Context) {

	// 使用这个绑定，直接报错
	var rp request.Page
	err := c.ShouldBindQuery(&rp)

	if err != nil {
		_ = c.Error(errors.OtherError("参数错误"))
		return
	}

	// 查询
	paginator, err := userService.UserPage(rp.Page, rp.PageSize)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.BuildPage{
		Code:  200,
		Msg:   "ok",
		Total: paginator.Total,
		Data:  paginator.Data,
	})
}

func queryUser(c *gin.Context) {

	query := c.Param("query")

	if query == "" || len(query) == 0 {
		_ = c.Error(errors.OtherError("查询条件错误"))
		return
	}

	user, err := userService.QueryUser(query)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.BuildPage{
		Code:  200,
		Msg:   "ok",
		Total: 1,
		Data:  user,
	})
}

func addUser(c *gin.Context) {

	var user models.UserDto
	err := c.ShouldBindJSON(&user)
	if err != nil {
		_ = c.Error(errors.OtherError("用户信息错误"))
		return
	}

	// dto序列化到user
	err = userService.AddUser(user.Serialization())
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "ok",
		Data: nil,
	})
}

func removeUser(c *gin.Context) {

	usn := c.Param("username")

	if usn == "" || len(usn) == 0 {
		_ = c.Error(errors.OtherError("用户名错误"))
		return
	}

	err := userService.RemoveUser(usn)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "ok",
		Data: nil,
	})
}
